<template>
  <div class="drawer-role">
    <a-drawer
      :width="510"
      :render-to-body="false"
      v-model:visible="isOpenRole"
      @ok="handelConfirm"
      :on-before-ok="verifyRoleName"
      unmount-on-close
      :closable="false"
      @close="handelClose"
    >
      <template #header>
        <CustomTitle title="新建角色" />
        <div style="display: flex; align-items: center; margin-bottom: 10px; margin-top: 28px">
          <span style="flex-shrink: 0; margin-right: 8px">角色名称</span>
          <a-input placeholder="请输入角色名称" v-model="addRoleForm.roleName" style="margin-right: 20px" />
          <a-select placeholder="参考其他角色权限" @change="copyPermissions as any">
            <a-option v-for="item in roles" :key="item.roleId" :value="item.roleId">{{ item.roleName }}</a-option>
          </a-select>
        </div>
        <div style="display: flex; align-items: center">
          <span style="flex-shrink: 0; margin-right: 8px">角色身份</span>
          <a-select placeholder="选择特定角色对应的身份，没有可不选" v-model="addRoleForm.roleGroup">
            <a-option v-for="item in identityOptions" :key="item.dictValue" :value="item.dictValue"
              >{{ item.dictLabel }}
            </a-option>
          </a-select>
        </div>
      </template>
      <div class="drawer-role__body">
        <div class="custom-tabs">
          <div
            class="tab-item"
            v-for="item in permissionTypes"
            :key="item.value"
            :class="addRoleFormPermissionType === item.value && 'tab-item-active'"
            @click="changePermissionType(item.value)"
          >
            {{ item.label }}
          </div>
        </div>
        <div class="drawer-role__body__content">
          <a-tree
            v-if="addRoleFormPermissionType === permissionType.MENU_PERMISSION"
            :checkable="true"
            check-strictly
            v-model:half-checked-keys="addHalfCheckPermissions"
            v-model:checked-keys="addRoleForm.menuIds"
            :checked-strategy="(checkedStrategy as any)"
            :data="addTreeData"
            :field-names="{ title: 'menuName', key: 'menuId' }"
          />
          <a-collapse v-else :default-active-key="[0, 1]" :bordered="false" expand-icon-position="right">
            <a-collapse-item v-for="(item, index) in addRoleDataScopeList" :key="index" :header="item.cnName">
              <a-list :bordered="false" :split="false">
                <a-radio-group v-model="item.selectedId">
                  <a-list-item v-for="subItem in item.items" :key="subItem.settingId">
                    <a-space>
                      <a-radio :value="subItem.settingId">
                        <a-list-item-meta :title="subItem.title"></a-list-item-meta>
                      </a-radio>
                    </a-space>
                  </a-list-item>
                </a-radio-group>
              </a-list>
            </a-collapse-item>
          </a-collapse>
        </div>
      </div>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { Message } from "@arco-design/web-vue";
import { cloneDeep } from "lodash";
import CustomTitle from "@/components/CustomTitle/index.vue";
import { dataScopeList, roleDataScopeList, roleMenuListId, getRoleList } from "@/apis";
import { menuTree } from "@/apis/user";
import type * as Role from "@/apis/role/type";
import { permissionType, permissionTypes } from "../../config";
const props = defineProps({
  modelValue: Boolean,
  identityOptions: Array
});
const emit = defineEmits(["update:modelValue", "handelConfirm", "handelClose"]);

const isOpenRole = computed({
  get() {
    return !!props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});
const addRoleDataScopeList = ref<Role.DataScopeList[]>([]);
const addRoleForm = ref({
  roleName: "",
  menuIds: [],
  roleDataPermissionSettingIds: []
});
// 半选项
const addHalfCheckPermissions = ref([]);
const checkedStrategy = ref("all");

/**
 * 查询角色列表
 */
const roles = ref<Role.RoleList[]>([]);
const roleName = ref("");
const getRoleListData = async () => {
  try {
    const { data } = await getRoleList({ name: roleName.value });
    roles.value = data || [];
  } catch (err) {
    console.log("查询角色列表>>>", err);
  }
};

/**
 * 切换权限类型
 */
const addRoleFormPermissionType = ref(permissionType.MENU_PERMISSION);
const addTreeData = ref([]) as any;
const changePermissionType = (type: string) => {
  addRoleFormPermissionType.value = type;
  addTreeData.value = type === permissionType.MENU_PERMISSION ? treeData.value : [];
};

/**
 * 去掉菜单多余的属性
 */
const removeMenuItemAttr = (arr: Array<any>): Array<any> => {
  return (
    arr?.map(v => {
      const { menuId, menuName, children } = v;
      return {
        children: children ? removeMenuItemAttr(children) : [],
        menuId,
        menuName
      };
    }) || []
  );
};
/**
 * 递归过滤出菜单子节点id
 * @param arr 菜单数组
 */
const menuChildNodeId = ref<string[]>([]);
const filterParent = (arr: any[]) => {
  arr.forEach((v: any) => {
    if (!v.children.length) {
      menuChildNodeId.value.push(v.menuId);
    } else {
      filterParent(v.children);
    }
  });
};
/**
 * 查询菜单树
 */
const treeData = ref<any[]>([]);
const getMenuTree = async () => {
  const { data } = await menuTree();
  treeData.value = removeMenuItemAttr(data);
  addTreeData.value = cloneDeep(treeData.value);
  filterParent(treeData.value);
};

/**
 * 查询数据权限
 */
const dataScopeLists = ref<Role.DataScopeList[]>([]);
let userRoleDataScope: string[] = [];
const getDataScopeList = async () => {
  const { data } = await dataScopeList();
  dataScopeLists.value = handelRoleEcho(data, userRoleDataScope);
  addRoleDataScopeList.value = cloneDeep(dataScopeLists.value);
};

/**
 * 处理角色数据
 * @param data
 * @param selectedIds
 */
const handelRoleEcho = (data: Role.DataScopeList[], selectedIds: string[]) => {
  return (
    data?.map((item: any) => {
      return {
        ...item,
        selectedId:
          item.items?.find((v: any) => {
            return selectedIds?.length ? selectedIds.includes(v.settingId) : v.isDefault;
          })?.settingId || ""
      };
    }) || []
  );
};

/**
 * 验证角色名称
 */
const verifyRoleName = () => {
  if (addRoleForm.value.roleName == "" || addRoleForm.value.roleName.trim() == "") {
    Message.error("请输入角色名称");
    return false;
  }
  if (addRoleForm.value.roleName.length > 20) {
    Message.error("角色名称不能超过20个字符");
    return false;
  }
  return true;
};

/**
 * 复制权限
 * @desc 选择其他角色并复制权限
 * @param value
 */
const copyPermissions = async (value: string) => {
  try {
    const { data: roleList } = await roleDataScopeList({ roleId: value });
    const { data: scopeList } = await dataScopeList();
    addRoleDataScopeList.value = handelRoleEcho(scopeList, roleList);
    // 此处赋值给新的角色权限
    const { data } = await roleMenuListId(value);
    addRoleForm.value.menuIds = data?.menuIds || [];
  } catch (err) {
    console.log(err, "<<<<copyPermissions");
  }
};

/**
 * 确定
 */
const handelConfirm = () => {
  // 角色数据权限id
  let roleDataPermissionSettingIds = addRoleDataScopeList.value?.map(v => v.selectedId) || [];
  let menuIds = [...addRoleForm.value.menuIds, ...addHalfCheckPermissions.value];
  emit("handelConfirm", { ...addRoleForm.value, roleDataPermissionSettingIds, menuIds });
};

/**
 * 关闭抽屉
 */
const handelClose = () => {
  emit("handelClose");
};

getRoleListData();
getDataScopeList();
getMenuTree();
</script>

<style scoped lang="scss">
@import "index";
</style>
